package com.lzh.persevere.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.persevere.mapper.ArticleInfoMapper;
import com.lzh.persevere.mapper.CollectArticleInfoMapper;
import com.lzh.persevere.mapper.TagInfoMapper;
import com.lzh.persevere.model.entity.CollectArticleInfo;
import com.lzh.persevere.model.qo.collectarticle.PageCollectArticle;
import com.lzh.persevere.model.vo.tag.ArticleTagInfoVO;
import com.lzh.persevere.service.CollectArticleInfoService;
import com.lzh.persevere.template.PageAbstractTemplate;
import com.lzh.persevere.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文章收藏信息表服务实现类
 *
 * @author luzhiheng
 * @since 2025-07-22
 */
@Service
public class CollectArticleInfoServiceImpl extends ServiceImpl<CollectArticleInfoMapper, CollectArticleInfo> implements CollectArticleInfoService {

    @Resource
    private ArticleInfoMapper articleInfoMapper;

    @Resource
    private TagInfoMapper tagInfoMapper;

    @Override
    public Map<String, Object> findCollectArticleList(PageCollectArticle qo) {
        Map<String, Object> otherQueryMap = new HashMap<>();
        Long userId = SecurityUtils.getUserId();
        otherQueryMap.put("userId", userId);
        PageAbstractTemplate template = new PageAbstractTemplate() {
            @Override
            public Integer countTotal() {
                return baseMapper.countList(getQueryMap(qo.getPageModel(), otherQueryMap));
            }

            @Override
            public List<Map<String, Object>> queryPageList() {
                List<Map<String, Object>> pageList = baseMapper.getPageList(queryMap);
                if (CollectionUtil.isNotEmpty(pageList)) {
                    List<Long> articleIdList = pageList.stream().map(e -> Long.valueOf(e.get("id").toString())).collect(Collectors.toList());
                    // 获取文章标签
                    List<ArticleTagInfoVO> tagInfoList = CollectionUtil.isNotEmpty(articleIdList) ? tagInfoMapper.selectByArticleIdList(articleIdList) : new ArrayList<>();
                    Map<Long, List<ArticleTagInfoVO>> articleIdTagMap = tagInfoList.stream().collect(Collectors.groupingBy(ArticleTagInfoVO::getArticleId));
                    pageList.forEach(e -> {
                        List<ArticleTagInfoVO> tagList = articleIdTagMap.get(Long.valueOf(e.get("id").toString()));
                        if (CollectionUtil.isNotEmpty(tagList)) {
                            e.put("articleTagList", tagList);
                        }
                    });
                }
                return pageList;
            }
        };
        return template.queryPage();
    }
}
